package com.spring.library.interceptor;

import com.alibaba.fastjson2.JSON;
import com.spring.library.entity.User;
import com.spring.library.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        System.out.println("token = " + token);
        //      redis中的令牌验证
        try {
            Object obj = redisTemplate.opsForValue().get(token);
//          放行
            if(obj!=null){
                ThreadLocalUtil.set(token);
                return true;
            }else{
                response.setStatus(401);
                return false;
            }
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }


    }
}
